package to_do

import (
	"context"
	"fmt"
	"github.com/micro/go-micro/v2/server"
	"kop/framework/errors"
	"kop/libs/database"
	"kop/pb"
	"kop/util/log"
	"time"
)

func NewWrapper(fn server.HandlerFunc) server.HandlerFunc {

	return func(ctx context.Context, req server.Request, rsp interface{}) (err error) {

		// 设计一个不用save entity
		// database.DB  DB指针取来
		// ctx.WithValue("DB", database.DB) // 存到ctx 里
		//

		var startTime = time.Now()

		var session = database.DB

		defer func() {

			if r := recover(); r != nil {

				switch e := r.(type) {
				case error:
					err = e
				case string:
					err = fmt.Errorf(e)
				default:
					err = fmt.Errorf("%v", e)
				}
			}

			if err != nil {

				//session.Rollback()

				log.Error("RPC [%s][%v] Error: %s", req.Method(), req.Body(), err.Error())

				err = errors.Parse(err)

			} else {

				//session.Commit()
			}
		}()

		var user pb.User
		if user, err = GetUser(ctx); err != nil {
			ctx = WithUser(ctx, user)
		}

		var model = NewModel(session)
		ctx = WithModel(ctx, model)

		if err = fn(ctx, req, rsp); err == nil {

			//if err = model.Save(); err == nil {
			log.Info("RPC [%s] Success, [%d] milliseconds", req.Method(), time.Now().Sub(startTime).Milliseconds())
			//}

		}

		return err
	}
}
